package LinkList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: LinkList
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-23  21:29
 * @Description: TODO
 * @Version: 1.0
 */
public class K个一组反转链表25 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween2(ListNode head, int left, int right) {
        ListNode dumpy = new ListNode(-1);
        dumpy.next = head;

        ListNode pre = dumpy;
        // 走在前一个位置来
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }
        ListNode curr = pre.next;
        ListNode future;
        // 表示在原地进行执政的变换 执行交换次数是right-left
        for (int i = 0; i < right - left; i++) {
            future = curr.next;
            curr.next = future.next;
            future.next = pre.next;
            pre.next = future;
        }
        return dumpy.next;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        int count = 0;
        ListNode curr = head;
        while (curr != null) {
            count++;
            curr = curr.next;
        }
        int index = 1;
        ListNode new_node = head;
        while (index < count && (index + k - 1) <= count) {
            new_node = reverseBetween2(new_node, index, index + k - 1);
            index += k;
        }
        return new_node;
    }
}
